import React, { useState, useEffect } from 'react';
import { IonCard, IonCardHeader, IonCardTitle, IonCardContent, IonButton, IonIcon, IonBadge, IonNote } from '@ionic/react';
import { refreshOutline, checkmarkCircle, alertCircle } from 'ionicons/icons';
import { useTranslation } from 'react-i18next';
import { terminalService } from '../../services/TerminalService';

interface Version {
  major: number;
  minor: number;
  patch: number;
}

const LATEST_VERSION: Version = {
  major: 0,
  minor: 1,
  patch: 17
};

const OllamaVersionCheck: React.FC = () => {
  const { t } = useTranslation();
  const [currentVersion, setCurrentVersion] = useState<Version | null>(null);
  const [isChecking, setIsChecking] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    checkVersion();
  }, []);

  const parseVersion = (versionStr: string): Version | null => {
    const match = versionStr.match(/(\d+)\.(\d+)\.(\d+)/);
    if (!match) return null;
    return {
      major: parseInt(match[1], 10),
      minor: parseInt(match[2], 10),
      patch: parseInt(match[3], 10)
    };
  };

  const checkVersion = async () => {
    setIsChecking(true);
    setError(null);
    try {
      const result = await terminalService.executeCommand('ollama --version');
      if (result.exitCode === 0) {
        const version = parseVersion(result.output);
        setCurrentVersion(version);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to check version');
    } finally {
      setIsChecking(false);
    }
  };

  const isOutdated = (): boolean => {
    if (!currentVersion) return false;
    
    if (currentVersion.major < LATEST_VERSION.major) return true;
    if (currentVersion.major === LATEST_VERSION.major && currentVersion.minor < LATEST_VERSION.minor) return true;
    if (currentVersion.major === LATEST_VERSION.major && 
        currentVersion.minor === LATEST_VERSION.minor && 
        currentVersion.patch < LATEST_VERSION.patch) return true;
    
    return false;
  };

  const handleUpdate = async () => {
    setIsChecking(true);
    setError(null);
    try {
      // For macOS and Linux
      const result = await terminalService.executeCommand('curl -fsSL https://ollama.ai/install.sh | sh');
      if (result.exitCode === 0) {
        await checkVersion();
      } else {
        setError(result.error || 'Update failed');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to update Ollama');
    } finally {
      setIsChecking(false);
    }
  };

  const getVersionString = (version: Version): string => {
    return `${version.major}.${version.minor}.${version.patch}`;
  };

  if (!currentVersion || !isOutdated()) return null;

  return (
    <IonCard className="mb-4">
      <IonCardHeader>
        <IonCardTitle className="flex items-center gap-2">
          {t('version.title')}
          <IonBadge color="warning">
            <IonIcon icon={alertCircle} />
            {t('version.status.outdated')}
          </IonBadge>
        </IonCardTitle>
      </IonCardHeader>
      <IonCardContent>
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm">{t('version.current')}: {getVersionString(currentVersion)}</p>
              <p className="text-sm">{t('version.latest')}: {getVersionString(LATEST_VERSION)}</p>
            </div>
            <IonButton
              onClick={handleUpdate}
              disabled={isChecking}
              color="primary"
            >
              <IonIcon slot="start" icon={refreshOutline} />
              {isChecking ? t('version.updating') : t('version.update')}
            </IonButton>
          </div>

          {error && (
            <IonNote color="danger" className="block mt-2">
              {error}
            </IonNote>
          )}

          <div className="text-sm">
            <p>{t('version.description')}</p>
            <a
              href="https://github.com/ollama/ollama/releases"
              target="_blank"
              rel="noopener noreferrer"
              className="text-primary hover:underline"
            >
              {t('version.releaseNotes')}
            </a>
          </div>
        </div>
      </IonCardContent>
    </IonCard>
  );
};

export default OllamaVersionCheck; 